package com.weavernorth.WeChatWork;

import com.alibaba.fastjson.JSONObject;
import com.weavernorth.util.Logger4jUtil;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import static com.weavernorth.util.HttpUtil.isHostReachable;

/**
 * @Author: zl
 * @Package: com.weavernorth.WeChatWork
 * @date: 2021/6/4 15:00
 * @description: 调用企业微信接口创建删除标签//implements Action {
 */
public class CreateOrDelTag implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {/*RequestInfo requestInfo*/
        Logger log = Logger4jUtil.getLoggerByName("/WeChatWork/CreateOrDelTag/");
        log.info("企业微信创建删除标签流程开始...");
        //企微接口地址：https://qyapi.weixin.qq.com/cgi-bin/gettoken
        //中转地址：https://www.erdosssl.cn/wework/cgi-bin/

        RecordSet rs = new RecordSet();
        //请求id
        String strRequestid = requestInfo.getRequestid();
        log.info("流程requestid=" + strRequestid);

        StringBuffer sbSql = new StringBuffer();
        List<String> ltTagJsons = new ArrayList<String>();
        sbSql.append("select * from FORMTABLE_MAIN_970 where REQUESTID =");
        sbSql.append(strRequestid);
        log.info("执行查询语句：" + sbSql);
        String Id = "";
        int XZSC = 0;//创建删除标记
        rs.executeQuery(sbSql.toString());
        while (rs.next()) {
            Id = Util.null2String(rs.getString("ID"));
            XZSC = rs.getInt("XZSC");
            log.info("ID：" + Id);
            log.info("创建删除标记：" + XZSC);
        }

        try {
            //企业微信API步骤一.获取AccessToken
            String param = "corpid=%s&corpsecret=%s&debug=1";
            param = String.format(param, HttpConst.corpid, HttpConst.corpsecret2);
            log.info("开始获取企业微信AccessToken...");
            String jsonAccessToken = HttpRequestUtil.sendGet(HttpConst.baseUrl + "gettoken", param,log);
            log.info("jsonAccessToken：" + jsonAccessToken);
            JSONObject jsonObject = JSONObject.parseObject(jsonAccessToken);
            int errcode = jsonObject.getIntValue("errcode");
            if (errcode != 0) {
                //始获取企业微信AccessToken失败
                requestInfo.getRequestManager().setMessagecontent("获取企业微信AccessToken失败：" + jsonAccessToken);
                return FAILURE_AND_CONTINUE;
            }
            String AccessToken = jsonObject.getString("access_token");
            log.info("AccessToken:" + AccessToken);
            StringBuffer sbJsonData = new StringBuffer();
            StringBuffer sbJsonUserList = new StringBuffer();
            String jsonResult = "";

            //企业微信API步骤二.根据手机号获取userid
            String postUrl = HttpConst.baseUrl + "user/getuserid?access_token=" + AccessToken;

            //查询明细
            sbSql.setLength(0);
            sbSql.append("select * from FORMTABLE_MAIN_970_DT1 where MAINID = ");
            sbSql.append(Id);
            rs.executeQuery(sbSql.toString());
            while (rs.next()) {
                String bqId = Util.null2String(rs.getString("BQIDQYWXY"));
                String[] splitSjh = Util.null2String(rs.getString("XGSJH")).split(",");
                //String sjhArr = Util.null2String(rs.getString("XGSJH"));
                for (int i = 0; i < splitSjh.length; i++) {
                    log.info("成员手机号：" + splitSjh[i]);
                    String strSJH = splitSjh[i];
                    sbJsonData.setLength(0);
                    sbJsonData.append("{ \"mobile\": \"");
                    sbJsonData.append(strSJH);
                    sbJsonData.append("\"}");
                    log.info("根据手机号获取用户ID【getuserid】JSON:" + sbJsonData);
                    jsonResult = HttpRequestUtil.sendPost(postUrl, sbJsonData.toString());
                    log.info("获取用户ID返回的JSON:" + jsonResult);
                    jsonObject = JSONObject.parseObject(jsonResult);

                    //请求修改标签USERLIST
                    sbJsonUserList.append("\"");
                    sbJsonUserList.append(jsonObject.getString("userid"));
                    sbJsonUserList.append("\"");
                    if ((i + 1) < splitSjh.length) {
                        sbJsonUserList.append(",");
                    }
                }
                sbJsonData.setLength(0);
                sbJsonData.append("{\"tagid\":");
                sbJsonData.append(bqId);
                sbJsonData.append(",\"userlist\":[");
                sbJsonData.append(sbJsonUserList);
                sbJsonData.append("]}");
                log.info("标签JSON列表：" + sbJsonUserList.toString());
                ltTagJsons.add(sbJsonData.toString());
            }
            postUrl = HttpConst.baseUrl + "tag/addtagusers?access_token=" + AccessToken;
            if (XZSC != 0) {
                postUrl = HttpConst.baseUrl + "tag/deltagusers?access_token=" + AccessToken;
            }
            for (int i = 0; i < ltTagJsons.size(); i++) {
                log.info("标签JSON报文：" + ltTagJsons.get(i));
                log.info("标签postUrl：" + postUrl);
                jsonResult = HttpRequestUtil.sendPost(postUrl, ltTagJsons.get(i));
                log.info("标签返回报文：" + jsonResult);
            }
            return SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            log.info(e.getMessage());
            requestInfo.getRequestManager().setMessagecontent("企业微信创建或者删除标签失败：" + e.toString());
            return FAILURE_AND_CONTINUE;
        }
    }
}